<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>文件上传客户端</title>
  </head>
  <body>
    <input id="file" type="file" />
    <script>
      const validateImage = (file) => {
        const size = 1 * 1024 * 1024; // 1MB
        const exts = [".jpg", ".jpeg", ".bmp", ".webp", ".gif", "png"];
        if (file.size > size) {
          console.log("文件过大");
          return false;
        }
        const name = file.name.toLocaleLowerCase();
        if (!exts.some((ext) => name.endsWith(ext))) {
          console.log("文件格式错误");
          return false;
        }
        return true;
      };
      file.onchange = function () {
        const fileList = this.files;
        // 如果未任何文件选中
        if (fileList.length === 0) {
          return;
        }
        const file = fileList[0];
        if (!validateImage(file)) {
          return;
        }

        // 预览图片文件
        const reader = new FileReader();
        reader.onload = (e) => {
          console.log(e.target.result);
        };
        reader.readAsDataURL(file);
      };
    </script>
  </body>
</html>
